package com.chenqi.community.aspect;

import com.chenqi.community.entity.RequestLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Ardai
 * 切面处理日志
 */
@Aspect
@Component
public class LogAspect {


    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //切入点
    @Pointcut("execution(* com.chenqi.community.controller.*.*(..))")
    public void log() {}
    //前置通知
    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        RequestLog requestLog = new RequestLog();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        String classMethods = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        requestLog.setUrl(url);
        requestLog.setIp(ip);
        requestLog.setClassMethod(classMethods);
        requestLog.setArgs(args);
        logger.info("RequestLog:{}",requestLog);
    }

    //后置通知
//    @After("log()")
//    public void doAfter() {
//        logger.info("==========doBefore==========");
//    }

    //返回通知
    @AfterReturning(returning = "result",pointcut = "log()")
    public void doAfterReturn(Object result) {
        logger.info("result {}",result);
    }
}
